<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Heater Manager</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        body {font-family: Arial, sans-serif;margin: 0;padding: 0;display: flex;justify-content: center;align-items: center;min-height: 100vh;background-color: #f5f5f5;}
        .container {width: 90%;max-width: 600px;background-color: white;padding: 20px;border-radius: 10px;box-shadow: 0 4px 6px rgba(0,0,0,0.1);}
        h1 {text-align: center;font-size: clamp(1.5rem, 3vw, 2.5rem);margin: 10px 0;}
        #value {text-align: center;font-size: clamp(2rem, 8vw, 4rem);margin: 20px 0;font-weight: bold;}
        #status_changed {text-align: center;font-size: clamp(0.9rem, 2vw, 1.2rem);color: red;margin: 15px 0;}
        .buttons {display: grid;grid-template-columns: repeat(5, 1fr);gap: 10px;margin-bottom: 20px;}
        input[type="submit"] {width: 100%;padding: 15px 5px;font-size: clamp(0.9rem, 2vw, 1.2rem);border: none;border-radius: 5px;cursor: pointer;transition: all 0.3s;color: white;text-shadow: 0 0 1px rgba(0,0,0,0.5);}
        input[value^="+"] {background-color: #f44336;}
        input[value^="+"]:hover {background-color: #d32f2f;}
        input[value^="-"] {background-color: #2196F3;}
        input[value^="-"]:hover {background-color: #0b7dda;}
        #submit_1 {background-color: #4CAF50;font-size: clamp(1rem, 2.5vw, 1.3rem);padding: 18px 5px;}
        #submit_1:hover {background-color: #45a049;}
        .submit-container {margin-top: 20px;display: flex;gap: 15px;justify-content: center;}
        #taskBtn {background-color: #FFC107;border-radius: 25px;padding: 18px 10px;font-size: clamp(1.1rem, 3vw, 1.6rem);flex: 1;max-width: 200px;}
        #taskBtn:hover {background-color: #FFA000;}
        #loading {text-align: center;font-size: clamp(1rem, 2vw, 1.5rem);color: #2196F3;margin: 10px 0;display: none;}
        #ws-status {text-align: center;font-size: clamp(0.8rem, 1.5vw, 1rem);color: #555;margin: 5px 0;}
    </style>
</head>
<body>
<div class="container">
    <h1>Heater Manager</h1>
    <p id="ws-status">WebSocket: Not Connected</p>
    <p id="loading">Connecting to WebSocket...</p>
    <p id="value">--</p>
    <p id="status_changed"></p>
    <div class="buttons">
        <input type="submit" value="+1" onclick="changeValue(1)">
        <input type="submit" value="+5" onclick="changeValue(5)">
        <input type="submit" value="+10" onclick="changeValue(10)">
        <input type="submit" value="+50" onclick="changeValue(50)">
        <input type="submit" value="+100" onclick="changeValue(100)">
        <input type="submit" value="-1" onclick="changeValue(-1)">
        <input type="submit" value="-5" onclick="changeValue(-5)">
        <input type="submit" value="-10" onclick="changeValue(-10)">
        <input type="submit" value="-50" onclick="changeValue(-50)">
        <input type="submit" value="-100" onclick="changeValue(-100)">
    </div>
    <div class="submit-container">
        <input type="submit" value="Submit" id="submit_1" name="submit" onclick="submitValue()">
        <input type="button" value="Task" id="taskBtn" onclick="window.location.href='/task'">
    </div>
</div>
<script>
    let lastTouchEnd = 0;
    document.addEventListener('touchend', function(event) {
        const now = (new Date()).getTime();
        if (now - lastTouchEnd <= 300) {
            event.preventDefault();
        }
        lastTouchEnd = now;
    }, false);
    document.addEventListener('gesturestart', function(event) {
        event.preventDefault();
    });
    let currentValue = 0;
    let originalValue = 0;
    let webSocket;
    let isConnected = false;
    let reconnectTimeout;
    const wsUrl = "ws://heater1.local:81";  // 需要根据设备不同修改
    function initWebSocket() {
        try {
            webSocket = new WebSocket(wsUrl);
            webSocket.onopen = onWebSocketOpen;
            webSocket.onmessage = onWebSocketMessage;
            webSocket.onclose = onWebSocketClose;
            webSocket.onerror = onWebSocketError;
        } catch (error) {
            console.error('WebSocket initialization error:', error);
            updateStatus('WebSocket: Connection Error');
            showLoading(false);
        }
    }
    function onWebSocketOpen() {
        isConnected = true;
        updateStatus('WebSocket: Connected');
        showLoading(false);
        console.log('WebSocket connection established');
        fetchCurrentValue();
    }
    function onWebSocketMessage(event) {
        try {
            const data = JSON.parse(event.data);
            console.log('Message received:', data);
            if (data.hasOwnProperty('ch')) {
                currentValue = parseInt(data.ch) || 0;
                originalValue = currentValue;
                document.getElementById("value").innerHTML = currentValue;
            } else if (data.hasOwnProperty('cm') && data.cm === 'ok') {
                document.getElementById("status_changed").innerHTML = "Value set successfully";
                originalValue = currentValue;
            }
        } catch (error) {
            console.error('JSON parse error:', error);
        }
    }
    function onWebSocketClose(event) {
        isConnected = false;
        updateStatus(`WebSocket: Disconnected (Code: ${event.code}, Reason: ${event.reason})`);
        console.log('WebSocket connection closed');
        scheduleReconnect();
    }
    function onWebSocketError(error) {
        isConnected = false;
        updateStatus('WebSocket: Error');
        console.error('WebSocket error:', error);
        scheduleReconnect();
    }
    function updateStatus(message) {
        document.getElementById("ws-status").innerHTML = message;
    }
    function showLoading(show) {
        const loadingElement = document.getElementById('loading');
        loadingElement.style.display = show ? 'block' : 'none';
    }
    function scheduleReconnect() {
        clearTimeout(reconnectTimeout);
        reconnectTimeout = setTimeout(() => {
            updateStatus('WebSocket: Reconnecting...');
            showLoading(true);
            initWebSocket();
        }, 3000);
    }
    document.addEventListener('DOMContentLoaded', initWebSocket);
    function fetchCurrentValue() {
        if (!isConnected) return;
        const message = JSON.stringify({path: 11});
        webSocket.send(message);
        console.log('Fetch current value request sent:', message);
    }
    function changeValue(delta) {
        currentValue += delta;
        if (currentValue > 100) currentValue = 100;
        if (currentValue < 0) currentValue = 0;
        document.getElementById("value").innerHTML = currentValue;
    }
    function submitValue() {
        if (!isConnected) {
            document.getElementById("status_changed").innerHTML = "WebSocket not connected, can't submit";
            return;
        }
        if (currentValue !== originalValue) {
            const statusElement = document.getElementById("status_changed");
            statusElement.innerHTML = "Submitting...";
            const message = JSON.stringify({path: 12, ch: currentValue});
            webSocket.send(message);
            console.log('Set value request sent:', message);
        } else {
            document.getElementById("status_changed").innerHTML = "No changes to submit";
        }
    }
</script>
</body>
</html>